import { useEffect, useMemo, useRef, useState } from 'react'
import { EditOutlined } from '@ant-design/icons'
import {
  Table,
  Image,
  Modal,
  Form,
  Space,
  Button,
  InputNumber,
  Input,
  message,
  Typography,
  Descriptions,
  Tag,
  notification,
} from 'antd'
import qsfLogo from '@/assets/images/logo.png'
import CustomDescriptions from '@/components/Descriptions'
import DetailContainer from '@/components/DetailContainer'
import {
  useAMDColumns,
  useMMDColumns,
  usebzflColumns,
  useqscdColumns,
  useCollectColumns,
  specDictVal,
} from './TableColumns'
import './detail.less'
import { IDes, QuotationCraftDetailVO, QuotationExcipientsDetailVO, QuotationMainDetailVO } from './types'
import { useSearchParams } from 'react-router-dom'
import { BadgeColorQuotationMap, QUOTATION_NEGOTATIATE_STATE_TEXT, QUOTATION_STATUS_TEXT } from '@/constant/goods'
import {
  editQuotationOrderDetail,
  getHistoryVersion,
  getQuotationOrderDetail,
  loadProduct,
  loadQuotationOrder,
  queryQuotationOrderByCode,
  rejectOrConfirmQuotation,
  rejectToWaitQuotation,
  reNegotiate,
  reportNegotiate,
  saveCraftDetail,
  saveExcipientsDetail,
  saveMainDetail,
  submitCheckPrice,
  submitNegotiatePrice,
  submitQuotationPrice,
} from '@/api/goods'
import { downloadByOwnUrl, getNameByOwnUrl } from '@/utils/util'
import * as mathjs from 'mathjs'
import useModal from '@/hooks/useModal'
import UploadFile from '@/components/UploadFile'
import useSearchFabric from '@/hooks/useSearchFabric'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import { useAppDispatch, useAppSelector } from '@/store/hooks'
import EditTable from './components/EditTable'
import { EditFormVertical } from '@/components/CustomForm'
import dayjs from 'dayjs'
import PermissionButton from '@/components/PermissionButton'
import { ItemType, MenuItemType } from 'antd/es/menu/interface'
import { applicationTypeEnum } from '@/constant'
import { changeMenuCollapsed } from '@/store/reducers/user'
const Index: React.FC = () => {
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [query] = useSearchParams()
  const dispatch = useAppDispatch()
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const { FabricOption, handleSearchFabric } = useSearchFabric()
  const { SupplierOption, handleSearchSupplier } = useSearchSupplier()
  const quotationOrderCode = query.get('quotationOrderCode') || null
  const quotationOrderId = query.get('quotationOrderId') || null
  const snapshotId = query.get('snapshotId') || null
  const [spinning, setspinning] = useState<boolean>(false)
  const [btnspinning, setbtnspinning] = useState<boolean>(false)
  const [isLoad, setisLoad] = useState<boolean>(false)
  //一键折叠
  const [isFold, setisFold] = useState<boolean>(false)
  const inputRef = useRef<any>(null)
  const [searchVal, setsearchVal] = useState('')
  const uploadModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      getDetail()
    },
  })
  const handleUploadPic = (event: any) => {
    event.stopPropagation()
    uploadModal.openModal()
  }
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [detailInfo, setdetailInfo] = useState<IDes>({})
  const [historyLatestInfo, sethistoryLatestInfo] = useState<IDes>({})
  const [tableData, settableData] = useState<QuotationMainDetailVO[]>([])
  const [qpedList, setqpedList] = useState<QuotationExcipientsDetailVO[]>([])
  const [qPackageedList, setqPackageedList] = useState<QuotationExcipientsDetailVO[]>([])
  const [qscdList, setqscdList] = useState<QuotationCraftDetailVO[]>([])
  const [isShowA, setisShowA] = useState(true)
  const [collectList, setcollectList] = useState<any[]>([
    {
      index: 0,
      name: '主料',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 1,
      name: '生产辅料',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 2,
      name: '包装辅料',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 3,
      name: '二次工艺',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 4,
      name: '加工费',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 5,
      name: '成本合计',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 6,
      name: '利润',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 7,
      name: 'A模式加点费用',
      bj: '',
      hj: '',
      hidden: false,
    },
    {
      index: 8,
      name: '总成本',
      bj: '',
      hj: '',
      hidden: false,
    },
  ])
  const [isEditTotal, setisEditTotal] = useState(false)
  const [profitmenuItems, setprofitmenuItems] = useState<ItemType<MenuItemType>[]>([])
  useEffect(() => {
    document.title = '报价单明细'
    if (window.innerWidth < 1500) {
      notification.open({
        type: 'warning',
        message: '为了提升您的浏览体验，建议调整页面缩放比例(快捷键：ctrl+减号)，以更好地查看页面信息。',
        duration: 3,
      })
    }
  }, [])
  useEffect(() => {
    getDetail()
    if (!snapshotId) {
      getHistoryLatestInfo()
    }
    dispatch(changeMenuCollapsed(true))
    const handleBeforeUnload = () => {
      dispatch(changeMenuCollapsed(false))
    }
    window.addEventListener('beforeunload', handleBeforeUnload)
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload)
      dispatch(changeMenuCollapsed(false))
    }
  }, [])
  const calculateSum = (list: any[], field: string) =>
    list?.reduce((pre, item) => mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.[field] || 0)).toString(), 0)
  const calculateSumLimit = (list: any[], field: string) => {
    const total = list?.reduce(
      (pre, item) => mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.[field] || 0)).toString(),
      0,
    )
    return mathjs.format(mathjs.bignumber(total), {
      notation: 'fixed',
      precision: 2,
    })
  }
  const updateCollectList = (tableData: any[], qpedList: any[], qPackageedList: any[], qscdList: any[]) => {
    const updatedCollectList = [...collectList]
    updatedCollectList[0] = {
      ...updatedCollectList[0],
      bj: calculateSum(tableData, 'money'),
      hj: calculateSum(tableData, 'checkMoney'),
    }
    updatedCollectList[1] = {
      ...updatedCollectList[1],
      bj: calculateSum(qpedList, 'money'),
      hj: calculateSum(qpedList, 'checkMoney'),
    }
    updatedCollectList[2] = {
      ...updatedCollectList[2],
      bj: calculateSum(qPackageedList, 'money'),
      hj: calculateSum(qPackageedList, 'checkMoney'),
    }
    updatedCollectList[3] = {
      ...updatedCollectList[3],
      bj: calculateSum(qscdList, 'money'),
      hj: calculateSum(qscdList, 'checkMoney'),
    }
    updatedCollectList[5] = {
      ...updatedCollectList[5],
      bj: calculateSum(updatedCollectList.slice(0, 5), 'bj'),
      hj: calculateSum(updatedCollectList.slice(0, 5), 'hj'),
    }
    const extraOneList = updatedCollectList.slice(0, 5).concat(updatedCollectList.slice(6, -1))
    updatedCollectList[8] = {
      ...updatedCollectList[8],
      bj: calculateSumLimit(extraOneList, 'bj'),
      hj: calculateSumLimit(extraOneList, 'hj'),
    }
    setcollectList(updatedCollectList)
  }
  useEffect(() => {
    updateCollectList(tableData, qpedList, qPackageedList, qscdList)
  }, [tableData, qpedList, qPackageedList, qscdList])
  useEffect(() => {
    updateCollectList(tableData, qpedList, qPackageedList, qscdList)
  }, [isEditTotal])
  // 根据大类处理利润的下拉菜单
  useEffect(() => {
    if (detailInfo && Object.keys(detailInfo).length > 0) {
      handleProfitMenu(detailInfo)
    }
  }, [detailInfo])
  const handleProfitMenu = (detailInfo: IDes) => {
    const bigClassId = detailInfo.bigClassId
    if (bigClassId == 125 || bigClassId == 1706) {
      //鞋子、袜子
      setprofitmenuItems([{ label: '8%成本', key: '0.08' }])
    } else if (bigClassId == 127) {
      //文胸
      setprofitmenuItems([{ label: '7%成本', key: '0.07' }])
    } else if (bigClassId == 128) {
      //床上用品
      setprofitmenuItems([
        { label: '13%加工费', key: '0.13' },
        { label: '7%成本', key: '0.07' },
        { label: '5%成本', key: '0.05' },
      ])
    } else {
      //内衣、成衣、小裤、家居服
      setprofitmenuItems([
        { label: '7%成本', key: '0.07' },
        { label: '5%集约成本+7%其他成本', key: 'spec' },
      ])
    }
  }
  const getDetail = async () => {
    setspinning(true)
    let res: any
    if (!snapshotId) {
      res = await getQuotationOrderDetail<IDes>({ quotationOrderCode, quotationOrderId }).finally(() =>
        setTimeout(() => {
          setspinning(false)
        }, 500),
      )
    } else {
      const result = await getHistoryVersion<IDes>({ quotationSnapshotId: snapshotId, quotationOrderId }).finally(() =>
        setTimeout(() => {
          setspinning(false)
        }, 500),
      )
      if (result?.data && result?.data?.data) {
        res = {
          code: 200,
          data: { ...result?.data?.data, createTime: result?.data?.createTime } || {},
        }
      }
    }
    if (res.code == 200) {
      setdetailInfo(res?.data)
      const quotationMainDetailList = res?.data?.quotationMainDetailList?.map((item: any, index: number) => {
        return {
          ...item,
          tempId: index,
        }
      })
      settableData(quotationMainDetailList || [])
      const quotationProduceExcipientsDetailList = res?.data?.quotationProduceExcipientsDetailList?.map(
        (item: any, index: number) => {
          return {
            ...item,
            tempId: index,
          }
        },
      )
      setqpedList(quotationProduceExcipientsDetailList || [])
      const quotationPackageExcipientsDetailList = res?.data?.quotationPackageExcipientsDetailList?.map(
        (item: any, index: number) => {
          return {
            ...item,
            tempId: index,
            // 净单耗、损耗、单件用量、核价用量、置灰
            fourDisabled: specDictVal?.includes(item?.excipientsName),
          }
        },
      )
      setqPackageedList(quotationPackageExcipientsDetailList || [])
      const quotationSecondCraftDetailList = res?.data?.quotationSecondCraftDetailList?.map(
        (item: any, index: number) => {
          return {
            ...item,
            tempId: index,
            // 用量、核价用量、置灰
            twoDisabled: ['运输费']?.includes(item?.craftPriceName),
          }
        },
      )
      setqscdList(quotationSecondCraftDetailList || [])
      // 加工费 报价 processPrice 核价 checkProcessPrice
      const jgfindex = collectList.findIndex((it) => it.index === 4)
      collectList[jgfindex]['bj'] = res?.data?.processPrice || 0
      collectList[jgfindex]['hj'] = res?.data?.checkProcessPrice || 0
      // 利润 报价 profit 核价 checkProfit
      const lrindex = collectList.findIndex((it) => it.index === 6)
      collectList[lrindex]['bj'] = res?.data?.profit || 0
      collectList[lrindex]['hj'] = res?.data?.checkProfit || 0
      setisShowA(!!res?.data?.aQuotation)
      // A模式 报价 aPrice 核价 checkAPrice
      const index = collectList.findIndex((it) => it.index === 7)
      collectList[index]['hidden'] = !res?.data?.aQuotation
      collectList[index]['bj'] = res?.data?.aQuotation ? res?.data?.aPrice : 0
      collectList[index]['hj'] = res?.data?.aQuotation ? res?.data?.checkAPrice : 0
      setcollectList([...collectList])
    }
  }
  const getHistoryLatestInfo = async () => {
    const result = await getHistoryVersion<IDes>({ quotationOrderId })
    if (result.data && result.data.data) {
      sethistoryLatestInfo(result?.data?.data || {})
    }
  }
  const handleSaveEditInfo = async (key: string, value?: any) => {
    detailInfo[key] = !detailInfo[key]
    setdetailInfo({ ...detailInfo })
    const target = key.replace('Edit', '')
    if (value) {
      const res = await editQuotationOrderDetail({ [target]: value, quotationOrderId })
      if (res.code == 200) {
        if (target === 'estimateOutBoxNum' || target === 'checkOutBoxNum') {
          autoUpdateCalc(target, value)
          return
        }
        message.success('操作成功')
        getDetail()
      }
    }
  }
  const autoUpdateCalc = async (target: 'estimateOutBoxNum' | 'checkOutBoxNum', value: string | number) => {
    const hasSpecqPackageedList = qPackageedList?.map((item) => {
      if (specDictVal?.includes(item?.excipientsName || '')) {
        const unitUsedNum =
          target === 'estimateOutBoxNum'
            ? value > 0
              ? mathjs.format(mathjs.divide(1, mathjs.bignumber(value || 0)), {
                  notation: 'fixed',
                  precision: 6,
                })
              : 0
            : item.unitUsedNum
        const money =
          target === 'estimateOutBoxNum'
            ? mathjs.format(mathjs.multiply(mathjs.bignumber(unitUsedNum), mathjs.bignumber(item?.unitPrice || 0)), {
                notation: 'fixed',
                precision: 4,
              })
            : item?.money

        const checkUsedNum =
          target === 'checkOutBoxNum'
            ? value > 0
              ? mathjs.format(mathjs.divide(1, mathjs.bignumber(value)), {
                  notation: 'fixed',
                  precision: 6,
                })
              : 0
            : item.checkUsedNum

        const checkMoney =
          target === 'checkOutBoxNum'
            ? mathjs.format(
                mathjs.multiply(mathjs.bignumber(checkUsedNum), mathjs.bignumber(item?.checkUnitPrice || 0)),
                {
                  notation: 'fixed',
                  precision: 4,
                },
              )
            : item.checkMoney

        return {
          ...item,
          unitConsumption: '0',
          waste: '0',
          unitUsedNum,
          money,
          checkUsedNum,
          checkMoney,
        }
      } else {
        return item
      }
    })
    const hasSpecqscdList = qscdList?.map((item) => {
      if (['运输费']?.includes(item?.craftPriceName || '')) {
        const useNum =
          target === 'estimateOutBoxNum'
            ? value > 0
              ? mathjs.format(mathjs.divide(1, mathjs.bignumber(value || 0)), {
                  notation: 'fixed',
                  precision: 6,
                })
              : 0
            : item.useNum
        const money =
          target === 'estimateOutBoxNum'
            ? mathjs.format(mathjs.multiply(mathjs.bignumber(useNum), mathjs.bignumber(item?.unitPrice || 0)), {
                notation: 'fixed',
                precision: 4,
              })
            : item?.money

        const checkUsedNum =
          target === 'checkOutBoxNum'
            ? value > 0
              ? mathjs.format(mathjs.divide(1, mathjs.bignumber(value)), {
                  notation: 'fixed',
                  precision: 6,
                })
              : 0
            : item.checkUsedNum

        const checkMoney =
          target === 'checkOutBoxNum'
            ? mathjs.format(
                mathjs.multiply(mathjs.bignumber(checkUsedNum), mathjs.bignumber(item?.checkUnitPrice || 0)),
                {
                  notation: 'fixed',
                  precision: 4,
                },
              )
            : item.checkMoney

        return {
          ...item,
          unitConsumption: '0',
          waste: '0',
          useNum,
          money,
          checkUsedNum,
          checkMoney,
        }
      } else {
        return item
      }
    })
    try {
      const result = await Promise.all([
        saveTableDataReq(
          hasSpecqPackageedList,
          'packageExcipientsDetailDTOList',
          saveExcipientsDetail,
          'PACKAGE',
          true,
        ),
        saveTableDataReq(hasSpecqscdList, 'craftDetailDTOList', saveCraftDetail, undefined, true),
      ])
      if (result?.every((item) => item?.code == 200)) {
        message.success('操作成功')
        getDetail()
      }
    } catch (error) {
      console.log('操作失败，请重试！')
    }
  }
  const editMoney = async (key: string, value: string) => {
    const res = await editQuotationOrderDetail({ [key]: value, quotationOrderId })
    if (res.code == 200) {
      message.success('操作成功')
      getDetail()
    }
  }
  const editPatternUrl = (vals: any) => {
    return editQuotationOrderDetail({ patternUrl: vals.fileId, quotationOrderId })
  }
  const saveTableDataReq = async (
    tableData: any[],
    key:
      | 'mainDetailDTOList'
      | 'packageExcipientsDetailDTOList'
      | 'produceExcipientsDetailDTOList'
      | 'craftDetailDTOList',
    req: (...set: any) => any,
    type?: 'PRODUCE' | 'PACKAGE',
    notshowToast?: boolean,
  ) => {
    // console.log(tableData, 'tableData')
    // if (!tableData || tableData.length === 0) return
    const data = type
      ? tableData.map((item) => {
          const { tempId, ...exectempId } = item
          return {
            ...exectempId,
            excipientsType: type,
          }
        })
      : tableData.map((item) => {
          const { tempId, ...exectempId } = item
          return {
            ...exectempId,
          }
        })
    const res = await req({ quotationOrderId, [key]: data, updateType: type })
    if (res.code == 200) {
      if (notshowToast) return res
      message.success('操作成功')
      getDetail()
    }
  }
  const operationThree = async (reqfunc: any) => {
    setbtnspinning(true)
    const res = await reqfunc({
      quotationOrderId,
    }).finally(() => setbtnspinning(false))
    if (res.code === 200) {
      message.success('操作成功')
      getDetail()
    }
  }
  const NegotiateModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
    },
    onReload: () => {
      getDetail()
    },
  })
  const grossProfitCalc = (detailInfo: any) => {
    if (!detailInfo?.tagPrice || !detailInfo?.negotiatePrice) return '-'
    const tagPrice = detailInfo?.tagPrice
    const negotiatePrice = detailInfo?.negotiatePrice
    try {
      // 计算毛利率 = (吊牌价 - 议价)/吊牌价 * 100
      const rate = mathjs.chain(tagPrice).subtract(negotiatePrice).divide(tagPrice).multiply(100).done()
      return (
        mathjs.format(rate, {
          notation: 'fixed',
          precision: 2,
        }) + '%'
      )
    } catch {
      return '-'
    }
  }
  const submitNewNegotiatePrice = async () => {
    const instance = Modal.confirm({
      title: '提交成交价',
      content: (
        <div>
          <div style={{ fontWeight: 500, fontSize: 16, marginBottom: 6 }}>
            请确认需要提交审批的成交价为：{detailInfo?.negotiatePrice || '-'}元
          </div>
          <div>*说明：若后期实际承运为七色纺集约物流，则对应该报价单运费扣除，返单若无检测对应扣除检测费</div>
        </div>
      ),
      width: 600,
      okText: '我已知悉并提交',
      cancelText: '取消',
      icon: null,
      onOk: async () => {
        const data = [{ quotationOrderId: quotationOrderId, quotationOrderCode: detailInfo?.quotationOrderCode }]
        const res = await submitNegotiatePrice(data).finally(() => instance.destroy())
        if (res.code === 200) {
          message.success('操作成功')
          getDetail()
        }
      },
    })
  }
  const rejectOrConfirmQuotationReq = async (rejectOrConfirm: 0 | 1) => {
    setbtnspinning(true)
    const data = [
      { quotationOrderId: quotationOrderId, quotationOrderCode: detailInfo?.quotationOrderCode, rejectOrConfirm },
    ]
    const res = await rejectOrConfirmQuotation(data).finally(() => setbtnspinning(false))
    if (res.code === 200) {
      message.success('操作成功')
      getDetail()
    }
  }
  const reNegotiateReq = async () => {
    setbtnspinning(true)
    const res = await reNegotiate({
      quotationOrderId,
    }).finally(() => setbtnspinning(false))
    if (res.code === 200) {
      message.success('操作成功')
      getDetail()
    }
  }
  const showBaseEdit = useMemo(() => {
    return (
      (detailInfo?.quotationStatus == 0 ||
        detailInfo?.quotationStatus == 1 ||
        (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) &&
      buttonCodeList?.includes('quotationBaseEdit') &&
      !snapshotId
    )
  }, [detailInfo, buttonCodeList, snapshotId])

  const showQuotationEdit = useMemo(() => {
    return (
      (detailInfo?.quotationStatus == 0 || (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) &&
      buttonCodeList?.includes('quotationEdit') &&
      !snapshotId
    )
  }, [detailInfo, buttonCodeList, snapshotId])

  const showCheckQuotationEdit = useMemo(() => {
    return (
      (detailInfo?.quotationStatus == 1 || (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) &&
      buttonCodeList?.includes('quotationcheckEdit') &&
      !snapshotId
    )
  }, [detailInfo, buttonCodeList, snapshotId])

  const showAddBtn = useMemo(() => {
    return (
      (detailInfo?.quotationStatus == 0 ||
        detailInfo?.quotationStatus == 1 ||
        (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) &&
      buttonCodeList?.includes('QuotationDetailAdd') &&
      !snapshotId
    )
  }, [detailInfo, buttonCodeList, snapshotId])

  const showDelBtn = useMemo(() => {
    return (
      (detailInfo?.quotationStatus == 0 ||
        detailInfo?.quotationStatus == 1 ||
        (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) &&
      buttonCodeList?.includes('QuotationDetailDel') &&
      !snapshotId
    )
  }, [detailInfo, buttonCodeList, snapshotId])

  const showMove = useMemo(() => {
    return (
      (detailInfo?.quotationStatus == 0 ||
        detailInfo?.quotationStatus == 1 ||
        (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) &&
      buttonCodeList?.includes('QuotationDetailMove') &&
      !snapshotId
    )
  }, [detailInfo, buttonCodeList, snapshotId])

  const showAction = useMemo(() => {
    return (
      (detailInfo?.quotationStatus == 0 ||
        detailInfo?.quotationStatus == 1 ||
        (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) &&
      (buttonCodeList?.includes('QuotationDetailAdd') || buttonCodeList?.includes('QuotationDetailDel')) &&
      !snapshotId
    )
  }, [detailInfo, buttonCodeList, snapshotId])

  const onAutoCalc = (rowKey: string, key: string, type: 'bj' | 'hj') => {
    const cbhjindex = collectList.findIndex((it) => it.index === 5)
    const lrindex = collectList.findIndex((it) => it.index === 6)
    const TotalCost = collectList[cbhjindex][type]
    if (key === 'spec') {
      const mainindex = collectList.findIndex((it) => it.index === 0)
      //集约的总金额
      const intensiveStatusCost = tableData
        ?.filter((item: QuotationMainDetailVO) => item?.intensiveStatus == 1)
        ?.reduce((pre, item) => pre + (type == 'bj' ? Number(item?.money) : Number(item?.checkMoney)), 0)
      //非集约的总金额
      const disintensiveStatusCost = collectList[mainindex][type] - Number(intensiveStatusCost)
      const otherCost = TotalCost - collectList[mainindex][type] + disintensiveStatusCost
      collectList[lrindex][type] = mathjs.format(
        mathjs.add(
          mathjs.multiply(mathjs.bignumber(intensiveStatusCost || 0), mathjs.bignumber(0.05)),
          mathjs.multiply(mathjs.bignumber(otherCost || 0), mathjs.bignumber(0.07)),
        ),
        {
          notation: 'fixed',
          precision: 4,
        },
      )
    } else if (key === '0.13') {
      // 加工费
      const jgfindex = collectList.findIndex((it) => it.index === 4)
      const processingCost = collectList[jgfindex][type]
      collectList[lrindex][type] = mathjs.format(
        mathjs.multiply(mathjs.bignumber(processingCost || 0), mathjs.bignumber(key || 0)),
        {
          notation: 'fixed',
          precision: 4,
        },
      )
    } else {
      collectList[lrindex][type] = mathjs.format(
        mathjs.multiply(mathjs.bignumber(TotalCost || 0), mathjs.bignumber(key || 0)),
        {
          notation: 'fixed',
          precision: 4,
        },
      )
    }
    editMoney(rowKey, collectList[lrindex][type])
  }
  const onAutoCalcAmode = (rowKey: string, key: string, type: 'bj' | 'hj') => {
    const totalindex = collectList.findIndex((it) => it.index === 5)
    const TotalCost = collectList[totalindex][type]
    const profitindex = collectList.findIndex((it) => it.index === 6)
    const ProfitCost = collectList[profitindex][type]
    const AmodeIndex = collectList.findIndex((it) => it.index === 7)
    collectList[AmodeIndex][type] = mathjs.format(
      mathjs.multiply(
        mathjs.add(mathjs.bignumber(TotalCost || 0), mathjs.bignumber(ProfitCost || 0)),
        mathjs.bignumber(key || 0),
      ),
      {
        notation: 'fixed',
        precision: 4,
      },
    )
    editMoney(rowKey, collectList[AmodeIndex][type])
  }
  const handleFillThreeProperty = (
    tableData: any[],
    settableData: React.Dispatch<React.SetStateAction<any[]>>,
    req: (...set: any) => any,
    target:
      | 'mainDetailDTOList'
      | 'packageExcipientsDetailDTOList'
      | 'produceExcipientsDetailDTOList'
      | 'craftDetailDTOList',
    type?: 'PRODUCE' | 'PACKAGE',
  ) => {
    // unitUsedNum / useNum -> checkUsedNum
    // unitPrice -> checkUnitPrice
    // money -> checkMoney
    const data = tableData?.map((item) => {
      return {
        ...item,
        checkUsedNum: item?.unitUsedNum || item?.useNum || null,
        checkUnitPrice: item?.unitPrice || null,
        checkMoney: item?.money || null,
      }
    })
    settableData([...data])
    return saveTableDataReq(data, target, req, type, true)
  }
  return (
    <DetailContainer>
      <div className="quotation_detail_header">
        <div className="qdh_left_con">
          <div className="qdh_left_con_text">{detailInfo?.quotationOrderCode}</div>
          {!snapshotId && (detailInfo?.quotationStatus || detailInfo?.quotationStatus == 0) && (
            <div style={{ marginLeft: 6 }}>
              <Tag color={BadgeColorQuotationMap[detailInfo?.quotationStatus]}>
                {QUOTATION_STATUS_TEXT[detailInfo?.quotationStatus]}
              </Tag>
            </div>
          )}
          {snapshotId && <div>（{'记录时间：' + (detailInfo?.createTime || '-')}）</div>}
        </div>
        {showCheckQuotationEdit && (
          <Button
            type="primary"
            onClick={async () => {
              try {
                const reqArr = [] as Promise<any>[]
                if (tableData.length > 0) {
                  reqArr.push(handleFillThreeProperty(tableData, settableData, saveMainDetail, 'mainDetailDTOList'))
                }
                if (qpedList.length > 0) {
                  reqArr.push(
                    handleFillThreeProperty(
                      qpedList,
                      setqpedList,
                      saveExcipientsDetail,
                      'produceExcipientsDetailDTOList',
                      'PRODUCE',
                    ),
                  )
                }
                if (qPackageedList.length > 0) {
                  reqArr.push(
                    handleFillThreeProperty(
                      qPackageedList,
                      setqPackageedList,
                      saveExcipientsDetail,
                      'packageExcipientsDetailDTOList',
                      'PACKAGE',
                    ),
                  )
                }
                if (qscdList.length > 0) {
                  reqArr.push(handleFillThreeProperty(qscdList, setqscdList, saveCraftDetail, 'craftDetailDTOList'))
                }
                const result = await Promise.all(reqArr)
                if (result?.every((item) => item?.code == 200)) {
                  message.success('操作成功')
                  getDetail()
                }
              } catch (error) {
                console.log('操作失败，请重试！')
              }
            }}
          >
            引用报价填充核价
          </Button>
        )}
        {!snapshotId &&
          Object.keys(detailInfo).length > 0 &&
          buttonCodeList?.includes('LoadQuotationFromSku') &&
          detailInfo?.quotationStatus == 0 && (
            <div className="qdh_center_con">
              <Button
                style={{ marginLeft: 12 }}
                value={searchVal}
                type="primary"
                onClick={async () => {
                  setisLoad(true)
                  await loadProduct({ quotationOrderId, quotationOrderCode }).finally(() => setisLoad(false))
                  message.success('数据加载成功')
                  getDetail()
                }}
                loading={isLoad}
              >
                从商品资料加载
              </Button>
            </div>
          )}
        {!snapshotId &&
          Object.keys(detailInfo).length > 0 &&
          buttonCodeList?.includes('LoadQuotation') &&
          detailInfo?.quotationStatus == 0 && (
            <div className="qdh_center_con">
              <Input.Search
                style={{ width: 320, marginLeft: 12 }}
                value={searchVal}
                placeholder="加载数据-从其他报价单加载"
                onChange={(event) => setsearchVal(event.target.value)}
                onSearch={async (quotationOrderCode) => {
                  if (!quotationOrderCode) return
                  setisLoad(true)
                  const res = await queryQuotationOrderByCode({ quotationOrderCode })
                    .catch(() => setisLoad(false))
                    .finally(() => setsearchVal(''))
                  if (res?.data) {
                    await loadQuotationOrder({ quotationOrderId, quotationOrderCode }).finally(() => setisLoad(false))
                    message.success('数据加载成功')
                    getDetail()
                  }
                }}
                enterButton="从报价单加载"
                loading={isLoad}
              />
            </div>
          )}
        {!snapshotId && (
          <div className="qdh_right_con">
            {detailInfo?.quotationStatus == 0 && (
              <PermissionButton
                permission="SubmitQuotation"
                type="primary"
                loading={btnspinning}
                onClick={() => operationThree(submitQuotationPrice)}
              >
                提交报价
              </PermissionButton>
            )}
            {detailInfo?.quotationStatus == 1 && (
              <PermissionButton
                permission="SubmitPricing"
                type="primary"
                loading={btnspinning}
                onClick={() => operationThree(submitCheckPrice)}
              >
                提交核价
              </PermissionButton>
            )}
            {detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1 && (
              <PermissionButton
                permission="ReportNegotiatePrice"
                type="primary"
                loading={btnspinning}
                onClick={() => NegotiateModal.openModal()}
              >
                汇报新议价
              </PermissionButton>
            )}
            {(detailInfo?.quotationStatus == 1 ||
              (detailInfo?.quotationStatus == 2 && detailInfo?.negotiateStatus == -1)) && (
              <PermissionButton
                permission="ReturnPendingQuotation"
                type="primary"
                danger
                loading={btnspinning}
                onClick={() => operationThree(rejectToWaitQuotation)}
              >
                驳回到待报价
              </PermissionButton>
            )}
            {detailInfo?.negotiateStatus == 0 && (
              <PermissionButton
                permission="SubmitFinalPrice"
                type="primary"
                loading={btnspinning}
                onClick={() => submitNewNegotiatePrice()}
              >
                提交成交价
              </PermissionButton>
            )}
            {detailInfo?.negotiateStatus == 1 && (
              <PermissionButton
                permission="SubmitDealPrice"
                type="primary"
                loading={btnspinning}
                onClick={() => rejectOrConfirmQuotationReq(1)}
              >
                确认成交价
              </PermissionButton>
            )}
            {(detailInfo?.negotiateStatus == 0 || detailInfo?.negotiateStatus == 1) && (
              <PermissionButton
                permission="ReturnDealPrice"
                type="primary"
                danger
                loading={btnspinning}
                onClick={() => rejectOrConfirmQuotationReq(0)}
              >
                驳回成交价
              </PermissionButton>
            )}
            {detailInfo?.negotiateStatus == 2 && (
              <PermissionButton
                permission="ReNegotiate"
                type="primary"
                loading={btnspinning}
                onClick={() => reNegotiateReq()}
              >
                重新议价
              </PermissionButton>
            )}
          </div>
        )}
      </div>
      <div className="quotation_detail_wrap">
        <div className="left_content">
          <CustomDescriptions title="基础信息">
            <Descriptions column={{ xxl: 6, xl: 5, lg: 4, md: 1, sm: 1, xs: 1 }} layout="vertical">
              {isRoot && (
                <Descriptions.Item style={{ paddingRight: 10 }} label="报价阶段" contentStyle={{ flexWrap: 'wrap' }}>
                  {detailInfo?.quotationStage || detailInfo?.quotationStage == 0
                    ? QUOTATION_NEGOTATIATE_STATE_TEXT[detailInfo?.quotationStage]
                    : '-'}
                </Descriptions.Item>
              )}
              <Descriptions.Item style={{ paddingRight: 10 }} label="开发季" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.seasonName}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="设计编码" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.designCode}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="工厂款号" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.factorySpuCode || '-'}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="款式编码" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.spuCode || '-'}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="商品名称" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.spuName || '-'}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="款式色" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.colorDetails && detailInfo?.colorDetails.length > 0 ? (
                  <div>
                    {detailInfo?.colorDetails?.reduce((acc: string, item: any, index: number) => {
                      return acc + (index === 0 ? '' : ',') + item?.colorDetailName
                    }, '')}
                  </div>
                ) : (
                  '-'
                )}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="下单数量" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.orderQty || '-'}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="供应商名称" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.supplierName || '-'}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="报价日期" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.quotationTime ? dayjs(detailInfo?.quotationTime).format('YYYY-MM-DD') : '-'}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="报价人员" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.quotationPerson || '-'}
              </Descriptions.Item>
              <Descriptions.Item style={{ paddingRight: 10 }} label="手机号" contentStyle={{ flexWrap: 'wrap' }}>
                {detailInfo?.phone || '-'}
              </Descriptions.Item>
              <Descriptions.Item
                style={{ paddingRight: 10 }}
                label={
                  <div>
                    <span>纸样</span>
                    {showBaseEdit && (
                      <span onClick={handleUploadPic}>
                        <EditOutlined style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }} />
                      </span>
                    )}
                  </div>
                }
                contentStyle={{ flexWrap: 'wrap' }}
              >
                <Typography.Link
                  onClick={() => {
                    if (detailInfo?.patternUrl) {
                      downloadByOwnUrl(detailInfo?.patternUrl)
                    }
                  }}
                >
                  {detailInfo?.patternUrl ? getNameByOwnUrl(detailInfo?.patternUrl) : '-'}
                </Typography.Link>
              </Descriptions.Item>
              <Descriptions.Item
                style={{ paddingRight: 10 }}
                label={
                  <div
                    onClick={() => {
                      showBaseEdit && handleSaveEditInfo('estimateOutBoxNumEdit')
                    }}
                  >
                    <span>预估外箱数</span>
                    {showBaseEdit && (
                      <span>
                        <EditOutlined style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }} />
                      </span>
                    )}
                  </div>
                }
                contentStyle={{ flexWrap: 'wrap' }}
              >
                <div style={{ padding: '0 30px 0 0' }}>
                  {detailInfo?.estimateOutBoxNumEdit ? (
                    <InputNumber
                      autoFocus
                      placeholder="请输入"
                      onBlur={(event: any) => {
                        handleSaveEditInfo('estimateOutBoxNumEdit', event?.target?.value)
                      }}
                      precision={0}
                      defaultValue={detailInfo?.estimateOutBoxNum}
                    ></InputNumber>
                  ) : (
                    detailInfo?.estimateOutBoxNum || '-'
                  )}
                </div>
              </Descriptions.Item>
              <Descriptions.Item
                style={{ paddingRight: 10 }}
                label={
                  <div
                    onClick={() => {
                      showCheckQuotationEdit && handleSaveEditInfo('checkOutBoxNumEdit')
                    }}
                  >
                    <span>核价外箱数</span>
                    {showCheckQuotationEdit && (
                      <span>
                        <EditOutlined style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }} />
                      </span>
                    )}
                  </div>
                }
                contentStyle={{ flexWrap: 'wrap' }}
              >
                <div style={{ padding: '0 30px 0 0' }}>
                  {detailInfo?.checkOutBoxNumEdit ? (
                    <InputNumber
                      autoFocus
                      placeholder="请输入"
                      onBlur={(event: any) => {
                        handleSaveEditInfo('checkOutBoxNumEdit', event?.target?.value)
                      }}
                      precision={0}
                      defaultValue={detailInfo?.checkOutBoxNum}
                    ></InputNumber>
                  ) : (
                    detailInfo?.checkOutBoxNum || '-'
                  )}
                </div>
              </Descriptions.Item>
              <Descriptions.Item
                style={{ paddingRight: 10 }}
                label={
                  <div onClick={() => showBaseEdit && handleSaveEditInfo('classRemarkEdit')}>
                    <span>品类备注</span>
                    {showBaseEdit && (
                      <span>
                        <EditOutlined style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }} />
                      </span>
                    )}
                  </div>
                }
                contentStyle={{ flexWrap: 'wrap' }}
              >
                <div style={{ padding: '0 30px 0 0' }}>
                  {detailInfo?.classRemarkEdit ? (
                    <div>
                      <Input
                        autoFocus
                        defaultValue={
                          detailInfo?.classRemark && detailInfo?.classRemark?.indexOf('/') > -1
                            ? detailInfo?.classRemark?.slice(detailInfo?.classRemark?.lastIndexOf('/') + 1)
                            : ''
                        }
                        onBlur={(event: any) => {
                          handleSaveEditInfo('classRemarkEdit', event?.target?.value)
                        }}
                        placeholder={
                          detailInfo?.bigClassId == '125'
                            ? '请输入针数、机型（开口机/一体机）等影响报价的信息'
                            : detailInfo?.bigClassId == '1706'
                            ? '请输入倍率等影响报价的信息'
                            : detailInfo?.bigClassId == '128'
                            ? '请输入工艺等影响报价的信息'
                            : '请输入影响报价的信息'
                        }
                      ></Input>
                    </div>
                  ) : (
                    <div>{detailInfo?.classRemark}</div>
                  )}
                </div>
              </Descriptions.Item>
              {isRoot && (
                <Descriptions.Item
                  style={{ paddingRight: 10 }}
                  label={
                    <div
                      onClick={() =>
                        buttonCodeList?.includes('quotationBaseEdit') &&
                        !snapshotId &&
                        detailInfo.quotationStatus != 3 &&
                        handleSaveEditInfo('priceErrorRemarkEdit')
                      }
                    >
                      <span>价格异常备注</span>
                      {buttonCodeList?.includes('quotationBaseEdit') &&
                        !snapshotId &&
                        detailInfo.quotationStatus != 3 && (
                          <span>
                            <EditOutlined style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }} />
                          </span>
                        )}
                    </div>
                  }
                  contentStyle={{ flexWrap: 'wrap' }}
                >
                  <div style={{ padding: '0 30px 0 0' }}>
                    {detailInfo?.priceErrorRemarkEdit ? (
                      <div>
                        <Input
                          autoFocus
                          defaultValue={detailInfo?.priceErrorRemark || ''}
                          onBlur={(event: any) => {
                            handleSaveEditInfo('priceErrorRemarkEdit', event?.target?.value)
                          }}
                          placeholder="请输入价格异常备注"
                        ></Input>
                      </div>
                    ) : (
                      <div>{detailInfo?.priceErrorRemark || '-'}</div>
                    )}
                  </div>
                </Descriptions.Item>
              )}
              {isRoot && (
                <Descriptions.Item style={{ paddingRight: 10 }} label="吊牌价" contentStyle={{ flexWrap: 'wrap' }}>
                  {detailInfo?.tagPrice || '-'}
                </Descriptions.Item>
              )}
              <Descriptions.Item
                style={{ paddingRight: 10 }}
                label={isRoot ? '最新议价 / 当前毛利率' : '最新议价'}
                contentStyle={{ flexWrap: 'wrap' }}
              >
                {isRoot
                  ? (detailInfo?.negotiatePrice || '-') + ' / ' + grossProfitCalc(detailInfo)
                  : detailInfo?.negotiatePrice || '-'}
              </Descriptions.Item>
              <Descriptions.Item
                style={{ paddingRight: 10 }}
                label={isRoot ? '最新报价 / 报价毛利率' : '最新报价'}
                contentStyle={{ flexWrap: 'wrap' }}
              >
                {isRoot
                  ? (detailInfo?.quotationPrice || '-') +
                    ' / ' +
                    (detailInfo?.quotationPriceProfitRate ? detailInfo?.quotationPriceProfitRate + '%' : '-')
                  : detailInfo?.quotationPrice || '-'}
              </Descriptions.Item>
              <Descriptions.Item
                style={{ paddingRight: 10 }}
                label={isRoot ? '最新核价 / 核价毛利率' : '最新核价'}
                contentStyle={{ flexWrap: 'wrap' }}
              >
                {isRoot
                  ? (detailInfo?.checkPrice || '-') +
                    ' / ' +
                    (detailInfo?.checkPriceProfitRate ? detailInfo?.checkPriceProfitRate + '%' : '-')
                  : detailInfo?.checkPrice || '-'}
              </Descriptions.Item>
            </Descriptions>
          </CustomDescriptions>
        </div>
        <div className="right_content">
          <div className="rc_image_box">
            <Image src={detailInfo?.imageUrl} fallback={qsfLogo}></Image>
          </div>
        </div>
      </div>
      <CustomDescriptions
        title="主料明细"
        extraButton={
          <Button
            size="small"
            type="primary"
            ghost
            loading={btnspinning}
            onClick={() => setisFold(!isFold)}
            style={{ marginLeft: 12 }}
          >
            {isFold ? '展开明细' : '折叠明细'}
          </Button>
        }
      >
        {!isFold && (
          <EditTable
            showAddBtn={showAddBtn}
            showQuotationEdit={showQuotationEdit}
            showCheckQuotationEdit={showCheckQuotationEdit}
            showMove={showMove}
            onSave={(data) => saveTableDataReq(data, 'mainDetailDTOList', saveMainDetail)}
            tableData={tableData}
            settableData={settableData}
            columns={useMMDColumns({
              snapshotId: !!snapshotId,
              onSave: (data) => saveTableDataReq(data, 'mainDetailDTOList', saveMainDetail),
              tableData,
              settableData,
              FabricOption,
              handleSearchFabric,
              SupplierOption,
              handleSearchSupplier,
              DICTDATA,
              inputRef,
              historyLatestInfo,
              detailInfo,
              showQuotationEdit,
              showCheckQuotationEdit,
              showAddBtn,
              showDelBtn,
              showAction,
              showBaseEdit,
            })}
            summary={
              tableData && tableData.length > 0
                ? (tableData) => (
                    <Table.Summary>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={0} align="center">
                          合计
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={14}></Table.Summary.Cell>
                        <Table.Summary.Cell index={2} align="center">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.money || 0)), {
                                notation: 'fixed',
                                precision: 2,
                              }),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={3} colSpan={3}></Table.Summary.Cell>
                        <Table.Summary.Cell index={4} align="center" className="title_bgc_spec_noflex">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(
                                mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.checkMoney || 0)),
                                {
                                  notation: 'fixed',
                                  precision: 2,
                                },
                              ),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={5} colSpan={1}></Table.Summary.Cell>
                      </Table.Summary.Row>
                    </Table.Summary>
                  )
                : undefined
            }
          ></EditTable>
        )}
      </CustomDescriptions>
      {!isFold && (
        <CustomDescriptions title="生产辅料明细">
          <EditTable
            showAddBtn={showAddBtn}
            showQuotationEdit={showQuotationEdit}
            showCheckQuotationEdit={showCheckQuotationEdit}
            showMove={showMove}
            onSave={(data) => saveTableDataReq(data, 'produceExcipientsDetailDTOList', saveExcipientsDetail, 'PRODUCE')}
            tableData={qpedList}
            settableData={setqpedList}
            columns={useAMDColumns({
              snapshotId: !!snapshotId,
              onSave: (data) =>
                saveTableDataReq(data, 'produceExcipientsDetailDTOList', saveExcipientsDetail, 'PRODUCE'),
              qpedList,
              setqpedList,
              DICTDATA,
              inputRef,
              historyLatestInfo,
              detailInfo,
              showQuotationEdit,
              showCheckQuotationEdit,
              showAddBtn,
              showDelBtn,
              showAction,
              showBaseEdit,
              isBras: detailInfo?.bigClassId == 127,
            })}
            summary={
              qpedList && qpedList.length > 0
                ? (tableData) => (
                    <Table.Summary>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={0} align="center">
                          合计
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={8}></Table.Summary.Cell>
                        <Table.Summary.Cell index={2} align="center">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.money || 0)), {
                                notation: 'fixed',
                                precision: 2,
                              }),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={3} colSpan={3}></Table.Summary.Cell>
                        <Table.Summary.Cell index={4} align="center" className="title_bgc_spec_noflex">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(
                                mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.checkMoney || 0)),
                                {
                                  notation: 'fixed',
                                  precision: 2,
                                },
                              ),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={5} colSpan={2}></Table.Summary.Cell>
                      </Table.Summary.Row>
                    </Table.Summary>
                  )
                : undefined
            }
          ></EditTable>
        </CustomDescriptions>
      )}
      {!isFold && (
        <CustomDescriptions title="包装辅料明细">
          <EditTable
            showAddBtn={showAddBtn}
            showQuotationEdit={showQuotationEdit}
            showCheckQuotationEdit={showCheckQuotationEdit}
            showMove={showMove}
            onSave={(data) => saveTableDataReq(data, 'packageExcipientsDetailDTOList', saveExcipientsDetail, 'PACKAGE')}
            tableData={qPackageedList}
            settableData={setqPackageedList}
            columns={usebzflColumns({
              snapshotId: !!snapshotId,
              onSave: (data) =>
                saveTableDataReq(data, 'packageExcipientsDetailDTOList', saveExcipientsDetail, 'PACKAGE'),
              qPackageedList,
              setqPackageedList,
              DICTDATA,
              inputRef,
              historyLatestInfo,
              detailInfo,
              showQuotationEdit,
              showCheckQuotationEdit,
              showAddBtn,
              showDelBtn,
              showAction,
              showBaseEdit,
            })}
            summary={
              qPackageedList && qPackageedList.length > 0
                ? (tableData) => (
                    <Table.Summary>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={0} align="center">
                          合计
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={8}></Table.Summary.Cell>
                        <Table.Summary.Cell index={2} align="center">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.money || 0)), {
                                notation: 'fixed',
                                precision: 2,
                              }),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={3} colSpan={3}></Table.Summary.Cell>
                        <Table.Summary.Cell index={4} align="center" className="title_bgc_spec_noflex">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(
                                mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.checkMoney || 0)),
                                {
                                  notation: 'fixed',
                                  precision: 2,
                                },
                              ),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={5} colSpan={1}></Table.Summary.Cell>
                      </Table.Summary.Row>
                    </Table.Summary>
                  )
                : undefined
            }
          ></EditTable>
        </CustomDescriptions>
      )}
      {!isFold && (
        <CustomDescriptions title="二次工艺明细">
          <EditTable
            showAddBtn={showAddBtn}
            showQuotationEdit={showQuotationEdit}
            showCheckQuotationEdit={showCheckQuotationEdit}
            showMove={showMove}
            onSave={(data) => saveTableDataReq(data, 'craftDetailDTOList', saveCraftDetail)}
            tableData={qscdList}
            settableData={setqscdList}
            columns={useqscdColumns({
              snapshotId: !!snapshotId,
              onSave: (data) => saveTableDataReq(data, 'craftDetailDTOList', saveCraftDetail),
              qscdList,
              setqscdList,
              DICTDATA,
              inputRef,
              historyLatestInfo,
              detailInfo,
              showQuotationEdit,
              showCheckQuotationEdit,
              showAddBtn,
              showDelBtn,
              showAction,
              showBaseEdit,
            })}
            summary={
              qscdList && qscdList.length > 0
                ? (tableData) => (
                    <Table.Summary>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={0} align="center">
                          合计
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={4}></Table.Summary.Cell>
                        <Table.Summary.Cell index={2} align="center">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.money || 0)), {
                                notation: 'fixed',
                                precision: 2,
                              }),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={3} colSpan={3}></Table.Summary.Cell>
                        <Table.Summary.Cell index={4} align="center" className="title_bgc_spec_noflex">
                          {tableData?.reduce(
                            (pre, item) =>
                              mathjs.format(
                                mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.checkMoney || 0)),
                                {
                                  notation: 'fixed',
                                  precision: 2,
                                },
                              ),
                            0,
                          )}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={5} colSpan={1}></Table.Summary.Cell>
                      </Table.Summary.Row>
                    </Table.Summary>
                  )
                : undefined
            }
          ></EditTable>
        </CustomDescriptions>
      )}
      <CustomDescriptions title="报价汇总">
        <Table
          bordered
          className="small_sise_customtable self_customtable_quotation"
          columns={useCollectColumns({
            collectList,
            setcollectList,
            isEditTotal,
            setisEditTotal,
            isShowA,
            editMoney,
            snapshotId: !!snapshotId,
            historyLatestInfo,
            detailInfo,
            showQuotationEdit,
            showCheckQuotationEdit,
            onAutoCalc,
            profitmenuItems,
            onAutoCalcAmode,
            isShowCalcBtn: buttonCodeList?.includes('QuotationAutoCalc'),
          })}
          pagination={false}
          dataSource={[...collectList.filter((item) => !item.hidden)]}
          rowKey="index"
          style={{ width: 600, flexShrink: 0 }}
        ></Table>
        {(detailInfo?.negotiateStatus == 1 || detailInfo?.negotiateStatus == 2) && (
          <div className="squotation_table_remark_box">
            <div className="strb_f16">供应商确认价格：{detailInfo?.negotiatePrice || '-'} 元</div>
            <div className="strb_f14">
              *说明：若后期实际承运为七色纺集约物流，则对应该报价单运费扣除，返单若无检测对应扣除检测费
            </div>
          </div>
        )}
      </CustomDescriptions>
      <Modal
        title="编辑纸样"
        open={uploadModal.open}
        maskClosable
        onCancel={uploadModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={uploadModal.closeModal}>取消</Button>
              <Button
                loading={uploadModal.confirmLoading}
                type="primary"
                onClick={() => uploadModal.handleSubmit(editPatternUrl)}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <Form className="upload_file_wrap" form={uploadModal.form} layout="vertical">
          <Form.Item label="纸样" name="fileId">
            <UploadFile max={1}></UploadFile>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="汇报新议价"
        open={NegotiateModal.open}
        maskClosable
        onCancel={NegotiateModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={NegotiateModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={NegotiateModal.confirmLoading}
                onClick={() =>
                  NegotiateModal.handleSubmit((vals) =>
                    reportNegotiate({
                      ...vals,
                      quotationOrderId,
                    }),
                  )
                }
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'newNegotiatePrice',
              label: '新议价',
              type: 'InputNumber',
              placeholder: '请输入新议价',
              rules: [
                {
                  required: true,
                  message: '请输入新议价',
                },
              ],
              config: {
                precision: 2,
                min: 0,
              },
            },
            {
              name: 'submitNegotiatePrice',
              label: '工厂可以提交当前议价作为成交价',
              type: 'Radio',
              option: [
                { label: '是', value: true },
                { label: '否', value: false },
              ],
            },
          ]}
          form={NegotiateModal.form}
          initialValues={{ submitNegotiatePrice: false }}
          header={
            <div style={{ marginBottom: 12 }}>
              <Descriptions column={4} layout="vertical">
                <Descriptions.Item style={{ paddingRight: 10 }} label="最新报价" contentStyle={{ flexWrap: 'wrap' }}>
                  {detailInfo?.quotationPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item style={{ paddingRight: 10 }} label="最新核价" contentStyle={{ flexWrap: 'wrap' }}>
                  {detailInfo?.checkPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item style={{ paddingRight: 10 }} label="最新议价" contentStyle={{ flexWrap: 'wrap' }}>
                  {detailInfo?.negotiatePrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item style={{ paddingRight: 10 }} label="吊牌价" contentStyle={{ flexWrap: 'wrap' }}>
                  {detailInfo?.tagPrice || '-'}
                </Descriptions.Item>
              </Descriptions>
            </div>
          }
        ></EditFormVertical>
      </Modal>
    </DetailContainer>
  )
}

export default Index
